package com.iot.core.manager.id;



import com.iot.core.data.mapper.HtTbIdMapper;
import com.iot.core.util.MyDateTime;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.iot.core.data.entity.table.HtTbidTableDef.HT_TBID;

public class HtIdManager {
    @Autowired
    SnowflakeIdWorker idWorker;
    @Autowired
    HtTbIdMapper htTbIdMapper;
    private static   HtIdManager instance = null;
    //2.构造方法设为 private
    public HtIdManager() {
        instance=this;
    }
    public static HtIdManager getInstance() {

        return instance;
    }


    public  long nextLong(){
        return idWorker.nextId();
    }
    public UUID nextGuid()
    {
        return UUID.randomUUID();
    }

    public String nextGuidStr()
    {
        return  nextGuid().toString().toLowerCase();
    }


    public Date LongIDToDate(long id)
    {
        var d = idWorker.getDateById(id);
        return d;
    }
    public   long DateToLongID(Date  dt)
    {
        return  idWorker.getIdByDate(dt);
    }


    Lock lock = new ReentrantLock();
    public   Long nextDBID(String name){
         var l=nextDBIDS(name,1);
         return l.get(0);
    }
    public List<Long> nextDBIDS(String name, int len){
        var l=new ArrayList<Long>();
        try {
            lock.lock();

            var m=htTbIdMapper.selectOneByCondition(HT_TBID.TNAME.eq(name));
            if (m.isIncludeDt())
            {
                if (m.isDayRestart())
                {
                    if (!m.getCurrentDt().equals(MyDateTime.todayShort() ) )
                    {
                        m.setCurrentDt(MyDateTime.todayShort());
                        m.setIdv(0L);
                    }
                }
                else
                {

                }

                for (var i = 0; i < len; i++)
                {
                    m.setIdv(m.getIdv()+1);
                    var r =(long)  ( Long.parseLong(m.getCurrentDt() ) * Math.pow(10, m.getIdLength())+m.getIdv() );
                    l.add(r);
                }
                htTbIdMapper.update(m,false);
                return l;
            }
            else
            {

                for (var i = 0; i < len; i++)
                {
                    m.setIdv(m.getIdv()+1);
                    var r =m.getIdv();
                    l.add(r);
                }

                htTbIdMapper.update(m,false);
                return l;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 必须在finally中释放
        }
        return l;
    }
}
